package ch01

import (
	"database/sql"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"log"
	"os"
	"time"
)

type Product struct {
	gorm.Model
	Code  string
	Price uint
}

type Con struct {
	Db *gorm.DB
}

func NewCon() (*Con, error) {

	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold: time.Second, // Slow SQL threshold
			LogLevel:      logger.Info, // Log level
			//IgnoreRecordNotFoundError: true,           // Ignore ErrRecordNotFound error for logger
			//ParameterizedQueries:      true,           // Don't include params in the SQL log
			Colorful: true, // Disable color
		},
	)
	// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
	dsn := "root:123456@tcp(127.0.0.1:3306)/gorm_test?charset=utf8mb4&parseTime=True&loc=Local"

	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			//TablePrefix: "t_",
			SingularTable: true, //取消表名复数s
		},
		Logger: newLogger,
	})
	return &Con{
		Db: db,
	}, err
}

func main() {

	con, _ := NewCon()
	db := con.Db
	_ = db.AutoMigrate(&Product{})

	db.Create(&Product{Code: "D42", Price: 202})
	db.Create(&Product{Code: "D43", Price: 203})

	var p = Product{}
	db.First(&p, 1) //主键查找

	fmt.Println(p)

	db.First(&Product{}, "code = ?", "D43") //条件查找

	db.Model(&Product{}).Where("Code = ? ", "D43").Update("Price", 300) //单字段更新
	//
	m := map[string]interface{}{"Price": 200, "code": sql.NullString{String: "", Valid: true}} //设置空值
	db.Model(&Product{}).Where("Code = ? ", "D43").Updates(m)                                  //多字段更新

	db.Delete(&Product{}, 1)

}
